// 引入模块依赖
const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');
const { ignoreUrl } = require('../config/constant')
// 过期时间(/毫秒)
const EXPIRE_TIME = 1000 * 60 * 30 //30分钟

//生成token
function getToken(id) {
	const created = Date.now();
	const cert = fs.readFileSync(path.join(__dirname, '../private_key/private.key'));//私钥 可以自己生成
	const token = jwt.sign(
		{
			id,
			exp: created + EXPIRE_TIME,
		},
		cert,
		{
			algorithm: 'RS256'
		});
	return token;
}

// 校验token
function verifyToken(token) {
	const cert = fs.readFileSync(path.join(__dirname, '../private_key/public.key'));//公钥 可以自己生成
	let res = false;
	try {
		let result = jwt.verify(token, cert, { algorithms: ['RS256'] }) || {};
		let { exp = 0 } = result, current = Date.now();
		if (current <= exp) res = true;
	} catch (e) {
		res = false;
	}
	return res;
}
// jwt认证的中间件
const jwtAuthMiddleware = (req, res, next) => {
	const token = req.headers.token;
	if (!token) {
		return res.status(401).json({ message: "暂无权限", code: 401 });
	}
	try {
		const pass = verifyToken(token);
		if (pass) {
			next();
		} else {
			return res.status(403).json({ message: "token已过期", code: 403 });
		}
	} catch (error) {
		res.status(403).json({ message: "token已过期", code: 403 });
	}
};

// 检查排除列表的中间件
const jwtAuthExclued = (req, res, next) => {
	// 检查请求 URL 是否在排除 jwtAuth 的列表里面
	const str = ignoreUrl.some(item => req.path.startsWith(item))
	if (str) {
		next(); // 在列表里，跳过后续中间件
	} else {
		jwtAuthMiddleware(req, res, next); // 不在列表里，就调用jwt中间件进行身份认证
	}
};
module.exports = {
	getToken,
	verifyToken,
	jwtAuthExclued
};

